package luoye.java.plugin;

import java.io.File;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;

public class JavassistUtils {
    ClassPool classPool;
    File file;

    public JavassistUtils(ClassPool classPool, File file) {
        this.classPool = classPool;
        this.file = file;
        findTarget();
    }

    private void findTarget(){
       String absolutePath = file.getAbsolutePath();
       findTarget(file,absolutePath);
   }
    private void findTarget(File dir, String fileName){
       if (dir.isDirectory()){
           // 如果是目录。
           for (File file : dir.listFiles()) {
               findTarget(file,fileName);
           }
       }else {
           // 表示是文件
           String filePath = dir.getAbsolutePath();
           if (!filePath.endsWith(".class")){
               return;
           }
           modify(filePath, fileName);
       }
    }

    private void modify(String filePath, String fileName) {
        if (filePath.contains("R$") || filePath.contains("R.class")
                || filePath.contains("BuildConfig.class")) {
            return;
        }
        String className =  filePath.replace(fileName, "").replace("\\", ".")  .replace("/", ".");

        String name = className.replace(".class", "").substring(1);
        CtClass ctClass= null;
        try {
            ctClass = classPool.getCtClass(name);
            addCode(ctClass, fileName,className);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加代码。
     * @param ctClass
     * @param fileName
     * @param className
     */
    private void addCode(CtClass ctClass, String fileName,String className) throws ClassNotFoundException {
        System.out.println("addCode:"+className);

        //Object[] annotations = ctClass.getAnnotation();
       /* for (Object object: annotations){
            System.out.println("annotations:"+object);
        }*/
    }
}
